'use client';

import { useState, useEffect } from 'react';
import dynamic from 'next/dynamic';

// 由于SSR问题，需要动态导入ReactPlayer
const ReactPlayer = dynamic(() => import('react-player/lazy'), {
  ssr: false,
  loading: () => (
    <div className="pt-[56.25%] w-full bg-gray-800 rounded-lg overflow-hidden relative">
      <div className="absolute inset-0 flex items-center justify-center">
        <div className="flex flex-col items-center">
          <svg className="animate-spin h-8 w-8 text-white mb-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
          </svg>
          <span className="text-white text-sm">加载播放器中...</span>
        </div>
      </div>
    </div>
  )
});

interface ReactVideoPlayerProps {
  url: string;
  title?: string;
  isLoading?: boolean;
  hasError?: boolean;
  hasTimeout?: boolean;
  onLoad?: () => void;
  onError?: () => void;
  onOpenInNewTab?: () => void;
}

export default function ReactVideoPlayer({
  url,
  title,
  isLoading = false,
  hasError = false,
  hasTimeout = false,
  onLoad,
  onError,
  onOpenInNewTab
}: ReactVideoPlayerProps) {
  const [playError, setPlayError] = useState(false);
  const [playing, setPlaying] = useState(false);
  const [retryCount, setRetryCount] = useState(0);

  useEffect(() => {
    // 重置状态
    setPlayError(false);
    setPlaying(false);
    setRetryCount(0);
  }, [url]);

  // 处理播放器就绪
  const handleReady = () => {
    if (onLoad) onLoad();
    setPlaying(true);
  };

  // 处理播放错误
  const handleError = (error: unknown) => {
    console.error("播放器错误:", error);
    setPlayError(true);
    if (onError) onError();
  };

  // 在新标签页打开
  const openInNewTab = () => {
    if (onOpenInNewTab) {
      onOpenInNewTab();
    } else if (url) {
      window.open(url, '_blank');
    }
  };

  // 重试播放
  const retryPlay = () => {
    setRetryCount(prev => prev + 1);
    setPlayError(false);
    if (onLoad) onLoad();
  };

  return (
    <div className="pt-[56.25%] w-full bg-gray-800 rounded-lg overflow-hidden relative">
      {/* 加载中显示 */}
      {isLoading && (
        <div className="absolute inset-0 z-20 flex items-center justify-center bg-gray-800">
          <div className="flex flex-col items-center">
            <svg className="animate-spin h-8 w-8 text-white mb-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
              <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
              <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            <span className="text-white text-sm">加载中...</span>
            <p className="text-gray-300 text-xs mt-2 max-w-xs text-center">正在加载解析后的视频，可能需要几秒钟...</p>
          </div>
        </div>
      )}
      
      {/* 加载超时显示 */}
      {hasTimeout && !hasError && !playError && (
        <div className="absolute inset-0 z-20 flex items-center justify-center bg-gray-800">
          <div className="flex flex-col items-center p-4 text-center">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-10 h-10 text-yellow-500 mb-2">
              <path strokeLinecap="round" strokeLinejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <p className="text-white font-medium mb-2">加载超时</p>
            <p className="text-gray-300 text-sm mb-3">当前解析接口响应较慢或视频可能不支持内嵌播放</p>
            <div className="flex gap-2">
              <button 
                onClick={openInNewTab}
                className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors flex items-center"
              >
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-4 h-4 mr-1">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 6H5.25A2.25 2.25 0 003 8.25v10.5A2.25 2.25 0 005.25 21h10.5A2.25 2.25 0 0018 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25" />
                </svg>
                在新标签页打开
              </button>
              {retryCount < 2 && (
                <button 
                  onClick={retryPlay}
                  className="px-4 py-2 bg-gray-700 text-white rounded-md hover:bg-gray-600 transition-colors flex items-center"
                >
                  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-4 h-4 mr-1">
                    <path strokeLinecap="round" strokeLinejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M15.485 4.355a8.25 8.25 0 00-13.803 3.7m0 0l-3.181-3.183m13.803 3.183 3.181 3.182" />
                  </svg>
                  重试加载
                </button>
              )}
            </div>
          </div>
        </div>
      )}
      
      {/* 错误显示 */}
      {(hasError || playError) && (
        <div className="absolute inset-0 z-20 flex items-center justify-center bg-gray-800">
          <div className="flex flex-col items-center p-4 text-center">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-10 h-10 text-red-500 mb-2">
              <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z" />
            </svg>
            <p className="text-white font-medium mb-2">播放器加载失败</p>
            <p className="text-gray-300 text-sm mb-3">当前视频可能不支持内嵌播放或解析接口无法正常工作</p>
            <div className="flex gap-2">
              <button 
                onClick={openInNewTab}
                className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors flex items-center"
              >
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-4 h-4 mr-1">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 6H5.25A2.25 2.25 0 003 8.25v10.5A2.25 2.25 0 005.25 21h10.5A2.25 2.25 0 0018 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25" />
                </svg>
                在新标签页打开
              </button>
              {retryCount < 2 && (
                <button 
                  onClick={retryPlay}
                  className="px-4 py-2 bg-gray-700 text-white rounded-md hover:bg-gray-600 transition-colors flex items-center"
                >
                  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-4 h-4 mr-1">
                    <path strokeLinecap="round" strokeLinejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M15.485 4.355a8.25 8.25 0 00-13.803 3.7m0 0l-3.181-3.183m13.803 3.183 3.181 3.182" />
                  </svg>
                  重试加载
                </button>
              )}
            </div>
          </div>
        </div>
      )}
      
      {/* React Player */}
      <div className="absolute inset-0">
        <ReactPlayer
          key={`${url}-${retryCount}`}
          url={url}
          width="100%"
          height="100%"
          playing={playing}
          controls={true}
          light={false}
          pip={true}
          stopOnUnmount={true}
          playsinline={true}
          onReady={handleReady}
          onError={handleError}
          config={{
            file: {
              attributes: {
                crossOrigin: "anonymous",
                referrerPolicy: "no-referrer"
              }
            },
            youtube: {
              playerVars: { 
                autoplay: 1,
                modestbranding: 1,
                rel: 0,
                showinfo: 0
              }
            }
          }}
          title={title || "视频播放器"}
        />
      </div>
    </div>
  );
} 